package com.captain.special.字符串;

/**
 * Des:
 *
 * @author XL
 * @Date 2022/4/5 15:31
 */
public class 反转字符串II541 {
    public String reverseStr(String s, int k) {
        if (k == 1) return s;
        char[] chars = s.toCharArray();
        //反转起位置
        int len = s.length();
        if (len / (2 * k) == 0) {
            reverseString(chars, 0, len - 1);
            return new String(chars);
        }
        //记录right的值,不满足步长时
        int left = 0;
        int right = -1;
        while (true) {
            //索引
            right = right + 2 * k;
            if (right > len - 1) {
                //最后的索引
                right = right - 2 * k;
                break;
            }
            reverseString(chars, left, left + k - 1);
            left = right + 1;
        }
        //处理最后的数据
        int totalIndexLen = len - 1;
        int remaining = totalIndexLen - right;
        if (remaining <= k) {
            right = totalIndexLen;
        } else {
            right = right + k;
        }
        reverseString(chars, left, right);
        return new String(chars);
    }

    public void reverseString(char[] s, int left, int right) {
        if (right > s.length - 1) right = s.length - 1;
        while (left <= right) {
            char temp = s[left];
            s[left] = s[right];
            s[right] = temp;
            left++;
            right--;
        }
    }
}
